package com.android.fragmentdemo.thread5

import org.junit.Test
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue

class Demo5 {
    @Test
    fun testProducerConsumer() {

        val blockingQueue = ArrayBlockingQueue<Goods>(5)
        val producerQueue = ProducerQueue(blockingQueue)
        val consumerQueue = ConsumerQueue(blockingQueue)

        Thread(producerQueue).start()
        Thread(consumerQueue).start()

        Thread.sleep(10 * 1000)
    }

    data class Goods(val brand: String, val name: String)

    class ProducerQueue(blockingQueue: BlockingQueue<Goods>) : Runnable {

        private val mBlockingQueue = blockingQueue

        override fun run() {
            for (i in 0..10) {

                val goods: Goods = if (i % 2 == 0) {
                    Goods("娃哈哈", "矿泉水")
                } else {
                    Goods("旺仔", "小馒头")
                }

                println("生产者开始生产商品:brand:${goods.brand},name:${goods.name}")

                try {
                    mBlockingQueue.put(goods)
                } catch (ex: InterruptedException) {
                    ex.printStackTrace()
                }
            }
        }
    }

    class ConsumerQueue(blockingQueue: BlockingQueue<Goods>) : Runnable {

        private val mBlockingQueue = blockingQueue

        override fun run() {
            for (i in 0..10) {
                try {
                    val goods = mBlockingQueue.take()
                    println("消费者消费的商品是:brand:${goods.brand},name:${goods.name}")

                    Thread.sleep(200)
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
            }
        }
    }
}